from django.contrib import admin
from .models import SubProject


@admin.register(SubProject)
class SubProjectAdmin(admin.ModelAdmin):
    """子项目管理"""
    list_display = (
        'name', 'project', 'manager', 'status', 'used_budget', 
        'created_by', 'completion_date', 'created_at'
    )
    list_filter = ('status', 'project', 'created_by', 'created_at')
    search_fields = ('name', 'description', 'manager', 'team_members')
    readonly_fields = ('created_at', 'updated_at')
    
    fieldsets = (
        ('基本信息', {
            'fields': ('project', 'name', 'description', 'manager', 'team_members')
        }),
        ('项目状态', {
            'fields': ('status', 'completion_date', 'used_budget')
        }),
        ('创建信息', {
            'fields': ('created_by', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def get_queryset(self, request):
        """优化查询"""
        return super().get_queryset(request).select_related('project', 'created_by')
    
    def save_model(self, request, obj, form, change):
        """保存时设置创建者"""
        if not change:  # 新建时
            obj.created_by = request.user
        super().save_model(request, obj, form, change)